package com.example.plat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.plat.enity.Comment;
import com.example.plat.exception.CommentException;
import com.example.plat.mapper.CommentMapper;
import com.example.plat.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    CommentMapper mapper;

    @Override
    public IPage<Comment> getComment(Long actId, Integer pageNum, Integer pageSize) {
        Page<Comment> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Comment> lqw = new LambdaQueryWrapper();
        lqw.eq(Comment::getActId,actId);
        lqw.orderByDesc(Comment::getTime);
        mapper.selectPage(page,lqw);
        return page;
    }

    @Transactional
    @Override
    public Comment createComment(Comment comment)throws CommentException {
        try {
            mapper.insert(comment);
            mapper.updateComment(comment.getActId());
        }catch (Exception e){
            throw new CommentException("发布评论失败！");
        }
        return comment;
    }

    @Transactional
    @Override
    public void deleteComment(Long commentId) throws CommentException {
        try {
            mapper.deleteById(commentId);
        }catch (Exception e){
            throw new CommentException("删除评论失败！");
        }
    }
}
